﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;
using Model;

namespace ACM
{
    public partial class SearchCarAdvance : BasePage
    {
        public int PageId
        {
            get { return Convert.ToInt32(hdfPageId.Value); }
            set { hdfPageId.Value = value.ToString(); }
        }
        public int RowPerPage
        {
            get { return Convert.ToInt32(hdfRowPerPage.Value); }
            set { hdfRowPerPage.Value = value.ToString(); }
        }
        public int TotalRow
        {
            get { return Convert.ToInt32(hdfTotalRow.Value); }
            set { hdfTotalRow.Value = value.ToString(); }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            grdResult.PageSize = Convert.ToInt16(ConfigurationManager.AppSettings["PageSize"]);
            RowPerPage = Convert.ToInt16(ConfigurationManager.AppSettings["PageSize"]);
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            ToSearch();
        }

        private void ToSearch()
        {
            PageId = 0;

            //Count result
            GetCarAdvanceCommand cmd = new GetCarAdvanceCommand(txtKeyword.Text, UIHelper.GetDateStringFromUI(txtSrtDate.Text)
                                    , UIHelper.GetDateStringFromUI(txtEndDate.Text), CurrentUser.dealer_code);
           
            cmd.Execute();

            TotalRow = cmd.ReccordCount;

            RenderPageNumber();
            ReSearch();

            pnlBottom.Visible = (CurrentUser.user_role == "tmt" && grdResult.Rows.Count > 0);
        }


        private void ReSearch()
        {
            //Search VIN found every user
            string dealer_code = CurrentUser.dealer_code;
            if (txtKeyword.Text != "") dealer_code = "";

            GetCarAdvanceCommand cmd = new GetCarAdvanceCommand(txtKeyword.Text, UIHelper.GetDateStringFromUI(txtSrtDate.Text)
                                    , UIHelper.GetDateStringFromUI(txtEndDate.Text), dealer_code, PageId.ToString()
                                    , RowPerPage.ToString());

            cmd.Execute();

            grdResult.DataSource = null;
            grdResult.DataSource = cmd.Result;
            grdResult.DataBind();
        }

       

        protected void rptPageItem_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            PageId = Convert.ToInt32(e.CommandArgument);
            ReSearch();
        }

        private void RenderPageNumber()
        {
            pnlPagination.Visible = false;

            if (TotalRow > 0)
            {
                int totalPage = (int)Math.Ceiling((decimal)TotalRow / (decimal)RowPerPage);

                if (totalPage > 1)
                {
                    pnlPagination.Visible = true;
                    DataTable dt = new DataTable();
                    dt.Columns.Add(new DataColumn("PageId", typeof(int)));
                    dt.Columns.Add(new DataColumn("PageNo", typeof(int)));

                    for (int i = 0; i < totalPage; i++)
                    {
                        DataRow dr = dt.NewRow();
                        dr["PageId"] = i;
                        dr["PageNo"] = i + 1;
                        dt.Rows.Add(dr);
                    }

                    rptPageItem.DataSource = dt;
                    rptPageItem.DataBind();
                }
            }
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;

            Response.AddHeader("content-disposition", "attachment;filename=TMTExport.csv");
            Response.Charset = "";
            Response.ContentEncoding = Encoding.UTF8;

            Response.ContentType = "application/text";
            Response.ContentEncoding = Encoding.Unicode;
            Response.BinaryWrite(Encoding.Unicode.GetPreamble());

            StringBuilder sb = new StringBuilder();
            sb.Append("VIN,รุ่นรถ,Model,Suffix,วันที่ตัดขายในระบบ,วันที่บันทึก");

            string dealer_code = CurrentUser.dealer_code;
            if (txtKeyword.Text != "") dealer_code = "";

            GetCarAdvanceCommand cmd = new GetCarAdvanceCommand(txtKeyword.Text, UIHelper.GetDateStringFromUI(txtSrtDate.Text)
                                   , UIHelper.GetDateStringFromUI(txtEndDate.Text), dealer_code, "-1"   // -1 means get reccord with no pagination
                                   , RowPerPage.ToString());

            cmd.Execute();

            if (cmd.Result != null)
            {
                foreach (acm_car_advance s in cmd.Result)
                {
                    sb.Append("\r\n");
                    sb.Append((s.vin != null ? s.vin.ToString() : "-") + ",");
                    sb.Append((s.car_series != null ? s.car_series.ToString() : "-") + ",");
                    sb.Append((s.car_sub_series != null ? s.car_sub_series.ToString() : "-") + ",");
                    sb.Append((s.car_model_suffix != null ? s.car_model_suffix.ToString() : "-") + ",");
                    sb.Append((s.sale_date != null ? s.sale_date.ToString("dd/MM/yyyy") : "-") + ",");
                    sb.Append((s.tx_date != null ? s.tx_date.Value.ToString("dd/MM/yyyy") : "-"));
                }

                Response.Output.Write(sb.ToString());
                Response.Flush();
                Response.End();
            }            
        }
    }
}